from django.shortcuts import render
from django import http
from django.views import View
from utility.views import LoginRequiredJsonMixin
from apps.orders.models import OrderInfo
from alipay import AliPay
from django.conf import settings
import os


# Create your views here.
class PaymentStatus(View):
    def put(self, request):
        pass


class PaymentView(LoginRequiredJsonMixin, View):
    def get(self, request, order_id):
        # 校验order_id是否存在
        try:
            # 要去支付的订单必须订单编号存在，而且必须是当前登录用户本人的订单，而且订单的状态必须是待支付
            order = OrderInfo.objects.get(order_id=order_id, user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数order_id错误'})

        """
        如果是安装的最新的支付宝SDK，读取秘钥的方式是读取秘钥字符串
        app_private_key_string = open("/path/to/your/private/key.pem").read()
        alipay_public_key_string = open("/path/to/alipay/public/key.pem").read()

        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        """
        # 对接支付宝的支付接口
        # 创建AliPay的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 应用的ID，如果对接的是沙箱应用，那么就是沙箱应用的ID。反之，就是正式应用的ID
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 使用AliPay的SDK对象调用支付的接口函数接口，得到收银台扫码登录路径order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 美多商城维护的订单号
            total_amount=str(order.total_amount),  # 实付款
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功后的回调地址
        )

        # 电脑网站支付，沙箱应用，需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
        # 电脑网站支付，正式应用，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'alipay_url': alipay_url})
